# Check the distribution of vote shares among first to fourth presidential candidates.
# See Appendix B.




##############
# vote share #
##############

library(brms)
library(ggplot2)
library(ggpubr)
library(stargazer)

# load presidential candidate data
load("PSRM Replication Files/PresidentialElections.Rdata")

# unique country and election year
pe$cy <- paste0(pe$pcountry, "_", pe$electionyear)

# calculate voteshares
pe$voteshare1 <- pe$vote_round1 / pe$validvote_round1
summary(pe$voteshare1)

# only use the first round
pe <- pe[-which(is.na(pe$voteshare1)),]

# candidate ranks
pe$rank <- NA
for(i in unique(pe$cy)){
  vs <- pe$voteshare1[which(pe$cy == i)]
  pe$rank[which(pe$cy == i)] <- order(vs, decreasing=TRUE)
}

pe$rank[pe$rank >= 5] <- NA

# keep top four candidates in each election
pe <- pe[-which(is.na(pe$rank)),]
table(pe$rank)

for(i in unique(pe$cy)){
  vs <- pe$voteshare1[which(pe$cy == i)][pe$rank[which(pe$cy == i)]]
  if(!all(diff(vs) < 0)){
    print(i)
  }
}

pe$type <- "First Placed (Winner)"
pe$type[pe$rank == 2] <- "Second Placed (Best Loser)"
pe$type[pe$rank == 3] <- "Third Placed"
pe$type[pe$rank == 4] <- "Fourth Placed"

pe$type <- factor(pe$type, levels=c("First Placed (Winner)", "Second Placed (Best Loser)", 
                                    "Third Placed", "Fourth Placed"))

# calculate average voteshares by candidate rank
(vsmeans <- data.frame(type=unique(pe$type), vsmean=tapply(pe$voteshare1, pe$type, mean)))
# First Placed (Winner)           First Placed (Winner) 0.45831129
# Second Placed (Best Loser) Second Placed (Best Loser) 0.28472936
# Third Placed                             Third Placed 0.12535594
# Fourth Placed                           Fourth Placed 0.06443061

# figure B.1
ggplot(data = pe, aes(x = voteshare1, group = type)) +
  geom_density() +
  geom_rug(sides = "b") +
  geom_vline(data = vsmeans, aes(xintercept=vsmean, group = type), 
             lwd=0.7, colour = "red") +
  facet_wrap(. ~ type, ncol = 1) + 
  xlab("Vote Share in the First Round") +
  ylab("Density") +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15),
        axis.title.y = element_text(size = 15))

#ggsave("voteshare_dist.pdf", width=7, height=8)
